﻿using System;
using Microsoft.AspNetCore.Mvc;
using WxOpenPLatCore.DBContext;
using WxOpenPLatCore.Interfaces;
using WxOpenPLatCore.Models;
using WxOpenPLatCore.Services;

namespace WxOpenPLatCore.Controllers
{
    public class AdminController : Controller
    {
        private readonly AdminService _service;
        public AdminController(AdminService service)
        {
            _service = (AdminService)service;
        }

        [HttpPost]
        public IActionResult Login()
        {
            string username = Request.Form["username"];
            string userpwd = Request.Form["userpwd"];
            Admin model = _service.Login(username, userpwd);
            if (model != null)
            {
                Response.Cookies.Append("token", model.LoginToken);
                return new JsonResult(new { sucess = true, info = "" });
            }
            else
            {
                return new JsonResult(new { sucess = false, info = "账号或密码不正确" });
            }
        }

        [HttpPost]
        public IActionResult Check()
        {
            string cookie = Request.Cookies["token"];
            if (string.IsNullOrEmpty(cookie))
            {
                return new JsonResult(new { sucess = false, info = "请先登录", tologin = true });
            }
            Admin model = _service.GetByToken(cookie);
            if (model == null)
            {
                return new JsonResult(new { sucess = false, info = "登陆已失效", tologin = true });
            }
            TimeSpan ts = DateTime.Now - model.loginDate.Value;
            if (ts.Days > 7)
            {
                return new JsonResult(new { sucess = false, info = "登陆已失效", tologin = true });
            }
            return new JsonResult(new { sucess = true, info = "", user = new { name = model.loginName, tname = model.loginTName } });

        }

        public IActionResult LognOut()
        {
            Response.Cookies.Delete("token");
            return new RedirectResult("/admin/Login.html");
        }
    }
}
